<!DOCTYPE html>
<html lang="zh-CN">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/apple-touch-icon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="description" content="安全行业从业者，主要方向PC逆向附带安卓和Linux逆向，时不时喜欢写点BUG代码">
  <meta name="author" content="Cray">
  <meta name="keywords" content="">
  <title>Powershell 官方例子 ~ 逆向安全博客</title>

  <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/5.12.1/css/all.min.css"  >
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css"  >
<link rel="stylesheet" href="https://cdn.staticfile.org/mdbootstrap/4.13.0/css/mdb.min.css"  >
<link rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/3.0.1/github-markdown.min.css"  >

<link rel="stylesheet" href="//at.alicdn.com/t/font_1067060_qzomjdt8bmp.css">



  <link rel="stylesheet" href="/lib/prettify/tomorrow.min.css"  >

<link rel="stylesheet" href="/css/main.css"  >


  <link rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css"  >


<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">


    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/">首页</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/archives/">归档</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/tags/">标签</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/links/">友链</a>
          </li>
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" false
      style="background: url('https://cdn.jsdelivr.net/gh/L0yy/tuchuang/Img/20200302232152.png') no-repeat center center;
      background-size: cover;">
    
        <div class="full-bg-img">
        <div class="mask rgba-black-light flex-center">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
                Powershell 官方例子
              
            </span>

            
              <br>
              

              <p>
                
                  
                  &nbsp;<i class="far fa-chart-bar"></i>
                  <span class="post-count">
                    1.1k 字
                  </span>&nbsp;
                

                
                  
                  &nbsp;<i class="far fa-clock"></i>
                  <span class="post-count">
                      5 分钟
                  </span>&nbsp;
                

                
                  <!-- 不蒜子统计文章PV -->
                  
                  &nbsp;<i class="far fa-eye" aria-hidden="true"></i>&nbsp;
                  <span id="busuanzi_container_page_pv">
                    <span id="busuanzi_value_page_pv"></span> 次
                  </span>&nbsp;
                
              </p>
            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="py-5 z-depth-3" id="board">
        <div class="post-content mx-auto" id="post">
          <div class="markdown-body">
            <h3 id="powershell-官方例子说明"><a href="#powershell-官方例子说明" class="headerlink" title="powershell 官方例子说明"></a>powershell 官方例子说明</h3><p>​    全部例子来源自<a target="_blank" rel="noopener" href="https://docs.microsoft.com/zh-cn/powershell/scripting/samples/sample-scripts-for-administration?view=powershell-7">示例脚本</a></p>
<h3 id="使用对象"><a href="#使用对象" class="headerlink" title="使用对象"></a>使用对象</h3><h4 id="查看对象结构-Get-Member"><a href="#查看对象结构-Get-Member" class="headerlink" title="查看对象结构 (Get-Member)"></a>查看对象结构 (Get-Member)</h4><blockquote>
<p> <code>Get-Process | Get-Member | Out-Host -Paging</code></p>
</blockquote>
<p>获取进程列表，再获取他们各自的成员信息，最后按页输出</p>
<blockquote>
<p> <code>Get-Process | Get-Member -MemberType Properties</code> </p>
<p>MemberType 的允许值有 AliasProperty、CodeProperty、Property、NoteProperty、ScriptProperty、Properties、PropertySet、Method、CodeMethod、ScriptMethod、Methods、ParameterizedProperty、MemberSet 以及 All。 </p>
</blockquote>
<h4 id="选择对象部件-Select-Object"><a href="#选择对象部件-Select-Object" class="headerlink" title="选择对象部件 (Select-Object)"></a>选择对象部件 (Select-Object)</h4><blockquote>
<p><code>Get-CimInstance -Class Win32_LogicalDisk | Select-Object -Property Name,FreeSpace</code></p>
</blockquote>
<p>利用WMI win32-logicaldisk类来获取服务器的磁盘空间使用率的信息，然后选择性的打印出 Name和FreeSpace两个项目</p>
<p>但是FreeSpace是 uint64格式的</p>
<pre><code class="powershell">Get-CimInstance -Class Win32_LogicalDisk |
  Select-Object -Property Name, @&#123;
    label=&#39;FreeSpace Cray&#39;
    expression=&#123;($_.FreeSpace/1GB).ToString(&#39;F2&#39;)&#125;
  &#125;</code></pre>
<p>第一行是获取基本数据，第二行是选择对象的属性，分别是Name和一个自定义的</p>
<p> <code>$_</code> 来指代管道中的当前对象 </p>
<p><code>ToString(&#39;F2&#39;)</code> 表示保留两位小数</p>
<h4 id="从管道中删除对象-Where-Object"><a href="#从管道中删除对象-Where-Object" class="headerlink" title="从管道中删除对象 (Where-Object)"></a>从管道中删除对象 (Where-Object)</h4><pre><code class="powershell">Get-CimInstance -Class Win32_SystemDriver |
  Where-Object &#123;$_.State -eq &quot;Running&quot;&#125; |
    Where-Object &#123;$_.StartMode -eq &quot;Manual&quot;&#125; |
      Format-Table -Property Name,DisplayName </code></pre>
<p><code>Where-Object</code> 作用就是筛选</p>
<table>
<thead>
<tr>
<th align="center">比较运算符</th>
<th align="center">含义</th>
<th align="center">示例（返回 True）</th>
</tr>
</thead>
<tbody><tr>
<td align="center">-eq</td>
<td align="center">等于</td>
<td align="center">1 -eq 1</td>
</tr>
<tr>
<td align="center">-ne</td>
<td align="center">不等于</td>
<td align="center">1 -ne 2</td>
</tr>
<tr>
<td align="center">-lt</td>
<td align="center">小于</td>
<td align="center">1 -lt 2</td>
</tr>
<tr>
<td align="center">-le</td>
<td align="center">小于或等于</td>
<td align="center">1 -le 2</td>
</tr>
<tr>
<td align="center">-gt</td>
<td align="center">大于</td>
<td align="center">2 -gt 1</td>
</tr>
<tr>
<td align="center">-ge</td>
<td align="center">大于或等于</td>
<td align="center">2 -ge 1</td>
</tr>
<tr>
<td align="center">-like</td>
<td align="center">相似（文本的通配符比较）</td>
<td align="center">“file.doc” -like “f*.do?”</td>
</tr>
<tr>
<td align="center">-notlike</td>
<td align="center">不相似（文本的通配符比较）</td>
<td align="center">“file.doc” -notlike “p*.doc”</td>
</tr>
<tr>
<td align="center">-contains</td>
<td align="center">包含</td>
<td align="center">1,2,3 -contains 1</td>
</tr>
<tr>
<td align="center">-notcontains</td>
<td align="center">不包含</td>
<td align="center">1,2,3 -notcontains 4</td>
</tr>
</tbody></table>
<pre><code class="powershell">Get-CimInstance -Class Win32_SystemDriver |
  Where-Object &#123;($_.State -eq &#39;Running&#39;) -and ($_.StartMode -eq &#39;Manual&#39;)&#125; |
    Format-Table -Property Name,DisplayName</code></pre>
<p>如果筛选条件有多个，可以使用逻辑运算符</p>
<p><code>Format-Table</code> 可以格式化最后的输出格式</p>
<table>
<thead>
<tr>
<th align="center">Logical and；如果两侧都为 True，则返回 True</th>
<th align="center">-and</th>
<th align="center">(1 -eq 1) -and (2 -eq 2)</th>
</tr>
</thead>
<tbody><tr>
<td align="center">Logical or；如果某一侧为 True，则返回 True</td>
<td align="center">-or</td>
<td align="center">(1 -eq 1) -or (1 -eq 2)</td>
</tr>
<tr>
<td align="center">Logical not；反转 True 和 False</td>
<td align="center">-not</td>
<td align="center">-not (1 -eq 2)</td>
</tr>
<tr>
<td align="center">Logical not；反转 True 和 False</td>
<td align="center">!</td>
<td align="center">!(1 -eq 2)</td>
</tr>
</tbody></table>
<h4 id="对对象进行排序-Sort-Object"><a href="#对对象进行排序-Sort-Object" class="headerlink" title="对对象进行排序( Sort-Object )"></a>对对象进行排序( Sort-Object )</h4><p>简单使用</p>
<pre><code class="powershell">Get-ChildItem |
  Sort-Object -Property CreationTime -Descending  |
  #Select-Object -Property Name,CreationTime
  Format-Table -Property Name,CreationTime</code></pre>
<p>运用哈希排序的复杂使用</p>
<pre><code class="powershell">Get-ChildItem |
  Sort-Object -Property @&#123; Expression = &#123; $_.LastWriteTime - $_.CreationTime &#125;; Descending = $true &#125; |
  Format-Table -Property LastWriteTime, CreationTime</code></pre>
<p>对目录中的文件，按最后写日期-创建日期大小进行降序排列</p>
<h4 id="创建-NET-和-COM-对象-New-Object"><a href="#创建-NET-和-COM-对象-New-Object" class="headerlink" title="创建 .NET 和 COM 对象 (New-Object)"></a>创建 .NET 和 COM 对象 (New-Object)</h4><p>创建某些COM对象</p>
<pre><code class="powershell">New-Object -ComObject WScript.Shell
New-Object -ComObject WScript.Network
New-Object -ComObject Scripting.Dictionary
New-Object -ComObject Scripting.FileSystemObject</code></pre>
<p>一个使用<strong>WScript.Shell</strong> 创建桌面快捷方式并执行</p>
<pre><code class="powershell">$WshShell = New-Object -ComObject WScript.Shell
$calclink = $WshShell.CreateShortcut(&quot;C:\Users\Cray\Desktop\calc.lnk&quot;)
$calclink.TargetPath = &quot;C:\WINDOWS\system32\calc.exe&quot;
$calclink.Save()
$WshShell.run(&quot;C:\Users\Cray\Desktop\calc.lnk&quot;)</code></pre>
<h4 id="使用静态类和方法"><a href="#使用静态类和方法" class="headerlink" title="使用静态类和方法"></a>使用静态类和方法</h4><p>静态类不能使用New-Object来创建</p>
<p>无需创建即可使用</p>
<p>使用时用**[ ]**调用，通常使用静态类的静态方法</p>
<pre><code class="powershell">[System.Environment] | Get-Member  #此类的详细信息
[System.Environment] | Get-Member -Static #查看静态成员</code></pre>
<p>调用方式使用  <strong>::</strong></p>
<pre><code class="powershell">[System.Environment]::OSVersion </code></pre>
<p>还有很多静态类，比如 math</p>
<pre><code class="powershell">PS&gt; [System.Math]::Sqrt(9)
3
PS&gt; [System.Math]::Pow(2,3)
8
PS&gt; [System.Math]::Floor(3.3)
3
PS&gt; [System.Math]::Floor(-3.3)
-4
PS&gt; [System.Math]::Ceiling(3.3)
4
PS&gt; [System.Math]::Ceiling(-3.3)
-3
PS&gt; [System.Math]::Max(2,7)
7
PS&gt; [System.Math]::Min(2,7)
2
PS&gt; [System.Math]::Truncate(9.3)
9
PS&gt; [System.Math]::Truncate(-9.3)
-9</code></pre>
<h4 id="获取-WMI-对象-Get-CimInstance"><a href="#获取-WMI-对象-Get-CimInstance" class="headerlink" title="获取 WMI 对象 (Get-CimInstance)"></a>获取 WMI 对象 (Get-CimInstance)</h4><blockquote>
<p>Windows Management Instrumentation (WMI) 是 Windows 系统管理的核心技术，因为它以统一的方式公开大量信息。 由于 WMI 可实现的效果，用于访问 WMI 对象的 PowerShell cmdlet <code>Get-CimInstance</code> 是进行实际工作最有用的对象之一 </p>
</blockquote>
<p>列出本机上可用的WMI类列表</p>
<pre><code class="powershell">Get-CimClass -Namespace root/CIMV2 |
  Where-Object CimClassName -like Win32* |
    Select-Object CimClassName</code></pre>
<p>使用WMI获取系统信息  Namespace 默认为 <code>root/CIMV2</code> </p>
<p><code>Get-CimInstance -Class Win32_OperatingSystem</code></p>
<p>他有很多属性，都可以查看。</p>
<p>例如</p>
<pre><code class="powershell"> Get-CimInstance -Class Win32_OperatingSystem | 
 select -Property Free*, @&#123;
 label = &quot;TotalVirtualMemorySize&quot; 
 expression = &#123;($_.TotalVirtualMemorySize/1MB).ToString(&quot;F0&quot;)&#125;&#125;  | Format-Table </code></pre>
<p>或者下面这样都是可以的</p>
<pre><code class="powershell">Get-CimInstance Win32_OperatingSystem |
Format-List Total*Memory*, Free*</code></pre>
<h3 id="管理计算机"><a href="#管理计算机" class="headerlink" title="管理计算机"></a>管理计算机</h3><p>该节有大量关于计算机的例子，建议直接看<a target="_blank" rel="noopener" href="https://docs.microsoft.com/zh-cn/powershell/scripting/samples/collecting-information-about-computers?view=powershell-7">官方文档</a></p>
<blockquote>
<p>若要完整显示具有极长名称的临时服务的名称，可能需要使用具有 AutoSize 和 Wrap 参数的 <code>Format-Table</code>，用于优化列宽并允许较长名称换行而不是被截断 </p>
</blockquote>

            <hr>
          </div>
          <br>
          <div>
            <p>
            
            
              <span>
                <i class="iconfont icon-tag"></i>
                
                  <a class="hover-with-bg" href="/tags/Shell/">Shell</a>
                
              </span>
            
            </p>
            
              <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://zh.wikipedia.org/wiki/Wikipedia:CC_BY-SA_3.0%E5%8D%8F%E8%AE%AE%E6%96%87%E6%9C%AC" rel="nofollow noopener noopener">CC BY-SA 3.0协议</a> 。转载请注明出处！</p>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container">
        <div id="toc">
  <p class="h5"><i class="far fa-list-alt"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>
      </div>
    
  </div>
</div>

<!-- custom -->


<!-- Comments -->
<div class="col-lg-7 mx-auto nopadding-md">
  <div class="container comments mx-auto" id="comments">
    
      <br><br>
      
      
  <div class="disqus" style="width:100%">
    <div id="disqus_thread"></div>
    <script>
      var disqus_config = function () {
        this.page.url = 'http://cve.gitee.io/cve/2020/04/12/Powershell 官方例子/';
        this.page.identifier = '/2020/04/12/Powershell 官方例子/';
      };
      var oldLoad = window.onload;
      window.onload = function () {
        var d = document, s = d.createElement('script');
        s.type = 'text/javascript';
        s.src = '//' + 'crayon-1' + '.disqus.com/embed.js';
        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
      };
    </script>
    <noscript>Please enable JavaScript to view the <a target="_blank" href="https://disqus.com/?ref_noscript" rel="nofollow noopener noopener">comments
        powered by Disqus.</a></noscript>
  </div>


    
  </div>
</div>

    
  </main>

  
    <a class="z-depth-1" id="scroll-top-button" href="#" role="button">
      <i class="fa fa-chevron-up scroll-top-arrow" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  <footer class="mt-5">
  <div class="text-center py-3">
    <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><b>Hexo</b></a>
    <i class="iconfont icon-love"></i>
    <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"> <b>Fluid</b></a>
    <br>

    
  
    <!-- 不蒜子统计PV -->
    
    &nbsp;<span id="busuanzi_container_site_pv"></span>总访问量 
          <span id="busuanzi_value_site_pv"></span> 次&nbsp;
  
  
    <!-- 不蒜子统计UV -->
    
    &nbsp;<span id="busuanzi_container_site_uv"></span>总访客数 
            <span id="busuanzi_value_site_uv"></span> 人&nbsp;
  
  <br>



    


    <!-- cnzz Analytics icon -->
    

  </div>
</footer>

<!-- SCRIPTS -->
<script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script src="https://cdn.staticfile.org/popper.js/1.16.1/umd/popper.min.js" ></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script src="https://cdn.staticfile.org/mdbootstrap/4.13.0/js/mdb.min.js" ></script>
<script src="/js/main.js" ></script>


  <script src="/js/lazyload.js" ></script>



  
  <script src="https://cdn.staticfile.org/tocbot/4.10.0/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var navHeight = $('#navbar').height();
      var toc = $('#toc');
      var main = $('main');
      var tocT = navHeight + (toc.offset().top - main.offset().top);
      var tocLimMin = main.offset().top - navHeight;
      var tocLimMax = $('#comments').offset().top - navHeight;
      $(window).scroll(function () {
        var scroH = document.body.scrollTop + document.documentElement.scrollTop;
        if (tocLimMin <= scroH && scroH <= tocLimMax) {
          toc.css({
            'display': 'block',
            'position': 'fixed',
            'top': tocT,
          });
        } else if (scroH <= tocLimMin) {
          toc.css({
            'position': '',
            'top': '',
          });
        } else if (scroH > tocLimMax) {
          toc.css('display', 'none');
        }
      });
      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '.post-content',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        scrollSmooth: true,
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc > p').css('visibility', 'visible');
      }
    });
  </script>







  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>


<!-- Plugins -->



  <script src="https://cdn.staticfile.org/prettify/188.0.0/prettify.min.js" ></script>
  <script>
    $(document).ready(function () {
      $('pre').addClass('prettyprint  linenums');
      prettyPrint();
    })
  </script>





  <script src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      getSearchFile(path);
      this.onclick = null
    }
  </script>



  <script src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <script>
    $("#post img:not(.no-zoom img, img[no-zoom])").each(
      function () {
        var element = document.createElement("a");
        $(element).attr("data-fancybox", "images");
        $(element).attr("href", $(this).attr("src"));
        $(this).wrap(element);
      }
    );
  </script>












</body>
</html>
